#define _GNU_SOURCE // This is necessary for the code to compile. Add it to the very top of your program.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>

// Copy this function into your code.
// You use it by passing it a pointer to a pthread_t and the number of cores
// that you want the thread limited to.
  
int limit_cores(pthread_t *thread, int num_cores)
{
  int s, j;
  cpu_set_t cpuset;

  // Set affinity mask to include CPUs 0 to (num_cores-1)

  CPU_ZERO(&cpuset);
  for (j = 0; j < num_cores; j++)
     CPU_SET(j, &cpuset);

  s = pthread_setaffinity_np(*thread, sizeof(cpu_set_t), &cpuset);
  if(s != 0)
  {
    printf("Error %i in pthread_setaffinity_np()...\n", s);
    return -1;
  }

  // Check the actual affinity mask assigned to the thread
  s = pthread_getaffinity_np(*thread, sizeof(cpu_set_t), &cpuset); 
  if(s != 0)
  {
    printf("Error %i in pthread_getaffinity_np()...\n", s);
    return -1;
  }

  // Check to see how many cores are assigned to the thread.
  int count = 0;
  for (j = 0; j < CPU_SETSIZE; j++)
  if (CPU_ISSET(j, &cpuset))
    count++;

  if(count > num_cores)
  {
    printf("Error, the thread seems to be using more cores than you requested...\n");
    return -2;
  }

  return 0;
}

int main(void)
{
  pthread_t thread = pthread_self();
  limit_cores(&thread, 2);
}

